package com.qinyi.admin.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.qinyi.common.ajax.AjaxCode;
import com.qinyi.common.annotation.DataSource;
import com.qinyi.common.constant.SecurityConstants;
import com.qinyi.common.enums.DataSourceType;
import com.qinyi.common.exception.CustomException;
import com.qinyi.system.service.ISysUserService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author wangan on 2019/5/31
 * @description
 */
@Controller
@RequestMapping("/captcha")
public class CaptchaController {

	@Autowired
	@Qualifier(value = "captchaProducer")
	private Producer captchaProducer;

	@Autowired
	@Qualifier(value = "captchaProducerMath")
	private Producer captchaProducerMath;

	@Autowired
	private ISysUserService userService;

	/**
	 * 校验数据randomStr 是否非空，生成验证码，保存
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@DataSource(value = DataSourceType.SLAVE)
	@GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX)
	public void createCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String type = request.getParameter("type");
		if (StringUtils.isEmpty(type)) {
			throw new CustomException(AjaxCode.SERVER_ERROR, "type不能为空");
		}
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		//生成验证码
		String value = null;
		String capStr;
		String capText;
		BufferedImage image = null;
		if (CAPTCHA_TYPE.MATH.getType().equals(type)) {
			capText = captchaProducerMath.createText();
			capStr = capText.substring(0, capText.lastIndexOf("@"));
			value = capText.substring(capText.lastIndexOf("@") + 1);
			image = captchaProducerMath.createImage(capStr);
		} else if (CAPTCHA_TYPE.CHAR.getType().equals(type)) {
			capText = captchaProducer.createText();
			capStr = value = capText;
			image = captchaProducer.createImage(capStr);
		}
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, value);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	public enum CAPTCHA_TYPE {
		MATH("math"),
		CHAR("char");
		private String type;

		CAPTCHA_TYPE(String s) {
			this.type = s;
		}

		public String getType() {
			return type;
		}
	}

}
